package flc.ast.fragment;

import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.provider.Settings;
import android.util.Log;
import android.view.View;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.TimeZone;

import flc.ast.R;
import flc.ast.activity.UseStateActivity;
import flc.ast.adapter.ScreenAppUseAdapter;
import flc.ast.bean.AppInformation;
import flc.ast.bean.StatisticsInfo;
import flc.ast.databinding.FragmentScreenUsageBinding;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ScreenUsageFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ScreenUsageFragment extends BaseNoModelFragment<FragmentScreenUsageBinding> {

    private ScreenAppUseAdapter mScreenAppUseAdapter;
    private int type;


    @Override
    protected int onCreate() {
        return R.layout.fragment_screen_usage;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);

        mDataBinding.tvStatistics.setOnClickListener(this);
        mDataBinding.tvUpdate.setOnClickListener(this);
        mDataBinding.tvToday.setOnClickListener(this);
        mDataBinding.tvWeek.setOnClickListener(this);
        mDataBinding.tvAppNoData.setOnClickListener(this);

        mDataBinding.rvAppList.setLayoutManager(new LinearLayoutManager(mContext));
        mScreenAppUseAdapter = new ScreenAppUseAdapter();
        mDataBinding.rvAppList.setAdapter(mScreenAppUseAdapter);
        mScreenAppUseAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        int id = v.getId();
        if (id == R.id.tvStatistics) {//统计
            AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
            int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), mContext.getPackageName());
            if (mode == AppOpsManager.MODE_ALLOWED) {
                startActivity(UseStateActivity.class);
            } else {
                ToastUtils.showShort(getString(R.string.no_permission));
            }
        } else if (id == R.id.tvUpdate) {//刷新
            getCurrentData(type);
            ToastUtils.showShort(R.string.refresh_success_tips);
        } else if (id == R.id.tvToday) {//今日
            type = 0;
            getCurrentData(type);
        } else if (id == R.id.tvWeek) {//本周
            type = 1;
            getCurrentData(type);
        } else if (id == R.id.tvAppNoData) {
            // 权限未授予
            AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
            int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), mContext.getPackageName());
            if (mode == AppOpsManager.MODE_ALLOWED) {
                // 权限已授予
                clearSelection();
                mDataBinding.tvToday.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.tvToday.setBackgroundColor(Color.parseColor("#797CDB"));
                mDataBinding.tvScreenTimeTip.setText(R.string.today_screen_time);
                getData(StatisticsInfo.DAY);
                mDataBinding.tvAppNoData.setVisibility(View.GONE);
            } else {
                new XPopup.Builder(mContext).hasShadowBg(true).hasBlurBg(false).asConfirm(getString(R.string.tp_tip), getString(R.string.pmsy_tips), new OnConfirmListener() {
                    @Override
                    public void onConfirm() {
                        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
                        startActivity(intent);
                    }
                }).show();
            }
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
    }

    private void getCurrentData(int position) {
        boolean hasPermission = false;
        AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
        int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), mContext.getPackageName());
        if (mode == AppOpsManager.MODE_ALLOWED) {
            hasPermission = true;
        }
        switch (position) {
            case 0:
                clearSelection();
                mDataBinding.tvToday.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.tvToday.setBackgroundColor(Color.parseColor("#797CDB"));
                mDataBinding.tvScreenTimeTip.setText(R.string.today_screen_time);
                if (hasPermission) getData(StatisticsInfo.DAY);
                break;
            case 1:
                clearSelection();
                mDataBinding.tvWeek.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.tvWeek.setBackgroundColor(Color.parseColor("#797CDB"));
                mDataBinding.tvScreenTimeTip.setText(R.string.week_screen_time);
                if (hasPermission) getData(StatisticsInfo.WEEK);
                break;
            default:
                break;
        }
    }


    private void getData(int style) {
        StatisticsInfo statisticsInfo = new StatisticsInfo(mContext, style);
        List<AppInformation> showList = statisticsInfo.getShowList();
        mScreenAppUseAdapter.setList(showList);
        // 输出总计时长
        long totalTime = statisticsInfo.getTotalTime();
        int progress = 0;
        switch (style) {
            case 0:
                progress = Math.round((totalTime * 100L / 1000L * 60 * 60 * 24));
                break;
            case 1:
                progress = Math.round((totalTime * 100L / 1000L * 60 * 60 * 24 * 7));
                break;
        }
        mDataBinding.pvProgress.setProgress(progress);
        mScreenAppUseAdapter.setTotalTime(totalTime);
        SimpleDateFormat sdf = new SimpleDateFormat("HH'h'mm'm'");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+0"));
        mDataBinding.tvScreenTime.setText(TimeUtils.millis2String(totalTime, sdf));
        if (showList != null && !showList.isEmpty()) {
        } else {
            Log.e("AppUsage", "No usage stats available");
        }
    }

    private void getData() {
        AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
        int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), mContext.getPackageName());
        if (mode == AppOpsManager.MODE_ALLOWED) {
            // 权限已授予
            clearSelection();
            mDataBinding.tvToday.setTextColor(Color.parseColor("#FFFFFF"));
            mDataBinding.tvToday.setBackgroundColor(Color.parseColor("#797CDB"));
            mDataBinding.tvScreenTimeTip.setText(R.string.today_screen_time);
            getData(StatisticsInfo.DAY);
            mDataBinding.tvAppNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.tvAppNoData.setVisibility(View.VISIBLE);
        }
    }

    private void clearSelection() {
        mDataBinding.tvToday.setTextColor(Color.parseColor("#808080"));
        mDataBinding.tvToday.setBackgroundColor(Color.parseColor("#323364"));
        mDataBinding.tvWeek.setTextColor(Color.parseColor("#808080"));
        mDataBinding.tvWeek.setBackgroundColor(Color.parseColor("#323364"));
    }

}